//
//  LBWEmoticonpageView.swift
//  weibo
//
//  Created by Limonwei on 15/12/15.
//  Copyright © 2015年 heima. All rights reserved.
//

//显示表情的cell视图

import UIKit

class LBWEmoticonpageView: UICollectionViewCell {
    
    //当前cell的显示数据
    var emoticons: [LBWEmoticon]? {
        didSet{
            //先隐藏所有按钮
            for value in emoticonButtons {
                value.hidden = true
            }
            //遍历表情数据的数组
            for(i,emoticon) in emoticons!.enumerate() {
                //设置显示数据
                let button = emoticonButtons[i]
                button.hidden = false
                button.emoticon = emoticon
                
            }
        }
    }
    
    //装有20个表情按钮的数组
    private lazy var emoticonButtons: [LBWEmoticonButton] = [LBWEmoticonButton]()
    
    var indexPath: NSIndexPath? {
        didSet{
            
            //判断最近使用表情label 隐藏
            recentInfoLabel.hidden = indexPath?.section != 0
            
        }
    }
    
    //初始化控件
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        
        //添加控件
        addEmoticonButtons()
        
        contentView.addSubview(deleteButton)
        
        contentView.addSubview(recentInfoLabel)
        
        recentInfoLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-10)
        }
        
        //添加长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: "longPressGes:")
        
        //将手势添加到contentView
        contentView.addGestureRecognizer(ges)
        
        
    }
    
    //添加表情按钮
    private func addEmoticonButtons(){
        
        for _ in 0..<LBWEmoticonNumOfPage {
            let button = LBWEmoticonButton()
            
            //添加按钮点击事件
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: .TouchUpInside)
            button.titleLabel?.font = UIFont.systemFontOfSize(34)
            contentView.addSubview(button)
            emoticonButtons.append(button)
        }
        
    }
    
    //在layoutSubview里调整20个表情按钮的大小与位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //拿到20个按钮,遍历设置frame
        let leftMargin: CGFloat = 5
        let bottonMargin: CGFloat = 25
        
        //计算表情按钮的宽度与高度
        let itemW = (width - leftMargin * 2) / CGFloat(LBWEmoticonsColOfPage)
        let itemH = (height - 25) / CGFloat(LBWEmoticonsRowOfPage)
        for (i,value) in emoticonButtons.enumerate() {
            //设置宽高
            value.size = CGSize(width: itemW, height: itemH)
            //求出当前按钮的行数与列数
            let col = i % LBWEmoticonsColOfPage
            let row = i / LBWEmoticonsColOfPage
            
            //设置每一个表情的x y 值
            value.x = CGFloat(col) * itemW + leftMargin
            value.y = CGFloat(row) * itemH
        }
        //调整删除按钮的位置大小
        deleteButton.size = CGSize(width: itemW, height: itemH)
        deleteButton.x = width - itemW - leftMargin
        deleteButton.y = height - itemH - bottonMargin
    }
    
    //按钮点击监听方法
    @objc private func longPressGes(ges: UILongPressGestureRecognizer){
        //通过一个location查找其对应的表情按钮
        func buttonWithLocation(location: CGPoint) -> LBWEmoticonButton? {
            for button in emoticonButtons {
                //判断点是否在当前
                if CGRectContainsPoint(button.frame, location){
                    //查找到了跳出循环
                    return button
                }
            }
            return nil
            
        }
        switch ges.state {
        case .Began,.Changed:
            //找到手势按下的点
            let location = ges.locationInView(contentView)
            //查找这个点在哪一个button范围
            if let targetButton = buttonWithLocation(location) {
                popView.hidden = false
                targetButton.showPopView(popView)
            }
        case .Ended:
            let location = ges.locationInView(contentView)
            //查找这个点在哪一个button范围内
            if let targetButton = buttonWithLocation(location) {
                emoticonButtonClick(targetButton)
            }
            popView.hidden = true
        default:
            popView.hidden = true
        }
    }
    
    //表情按钮点击
    @objc private func emoticonButtonClick(button: LBWEmoticonButton){
        
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(LBWEmoticonButtonDidSelectedNotification, object: nil, userInfo: ["emoticon":button.emoticon!])
        //将当前表情按钮对应的模型保存到最近表情数组中去
        LBWEmoticonTools.shareTools.saveRecent(button.emoticon!)
        
        //弹出PopView
        let popView = LBWEmoticonPopView.popView()
        
        button.showPopView(popView)
        
        //设置多长时间后popView消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            popView.removeFromSuperview()
        })
    }
    
    //删除按钮点击
    @objc private func deleteButtonClick(){
        //通知
        NSNotificationCenter.defaultCenter().postNotificationName(LBWMDeleteButtonDidSelectedNotification, object: nil)
    }
    
    //懒加载控件
    //删除按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        
    
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
        
        //添加按钮点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    
    }()
    
    //最近视同表情的label
    private lazy var recentInfoLabel : UILabel = {
    
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        
        label.text = "最近使用的表情"
        
        return label
    
    }()
    
    //初始化PopView
    private lazy var popView: LBWEmoticonPopView = LBWEmoticonPopView.popView()
}






















